import sys, os
try:
        import pygtk
        pygtk.require("2.0")
except:
        pass
try:
        import gtk
        import gtk.glade
except:
        sys.exit(1)
from simpledcpp.gui.widgets.list import FavoritesTree
from xml.sax import make_parser
from xml.sax.handler import ContentHandler

class SaxHandler(ContentHandler):
        """ Callback class for SAX parser """
	setdict = {}
        chars = ""
        current_element = None
	
	def __init__(self):
		self.setdict = {}
		self.chars = ""
		self.current_element = ""

        def startElement(self,name,attrs):
                """ Handle for element begin """
                if name == "p":
                        propname = attrs.get('name')
                        self.current_element = propname

        def endElement(self,name):
                """ Handle for finished element """
                if (not self.current_element=="") :
                        self.setdict[self.current_element] = self.chars
                self.chars = ""
                self.current_element = ""

        def characters (self,ch):
                """ Handle for character data """
                sch = ch.lstrip()
                if not sch == "":
                        self.chars = sch


class FavoritesDialog:
	def __init__(self, parent):
		self.parent = parent
		self._widget = self.parent.wtree.get_widget("FavoritesDialog")
		self._addwidget = self.parent.wtree.get_widget("FavoritesAddDialog")
		self._addentry = self.parent.wtree.get_widget("FavoritesAddEntry")
		self._addcheck = self.parent.wtree.get_widget("FavoritesAddCheck")
		self.Box = self.parent.wtree.get_widget("FavoritesVBOX")
                menu_items = (
                ("/_" + _("Remove"),"Remove",self._remove, 0 , None),
                )
                self.tree= FavoritesTree(menu_items)

		self.parent._fastConnect("FavoritesOk", "clicked", self.ok)
		self.parent._fastConnect("FavoritesClear","clicked",self.tree.clear)
		self.parent._fastConnect("FavoritesAdd","clicked",self.show_add)
		self.parent._fastConnect("FavoritesDel","clicked",self._remove)
		self.parent._fastConnect("FavoritesAddCancel", 'clicked', self.hide_add)
		self.parent._fastConnect("FavoritesAddOk",'clicked', self.add_ok)
		self.Box.pack_start(self.tree.widget)
		self._load()

	def show_add(self, *args, **kwargs):
		self._addwidget.show()
		self._addentry.set_text("")

	def hide_add(self, *args, **kwargs):
		self._addwidget.hide()

	def show(self, *args, **kwargs):
		self._widget.show()

	def hide(self, *args, **kwargs):
		self._widget.hide()

	def ok(self, *args, **kwargs):
		self.hide()
		self._save()

	def _autoconnect(self):
		for row in self.tree.Rows():
			if row[1]:
				self.parent._connectTo(row[0])

	def _save(self, filename = None):
		if filename == None:
			filename = os.path.join(os.getenv("HOME"), ".simpledcpp/favorites.xml")
		self.tree._save(filename)

	def _load(self, filename = None):
                if filename == None:
                        filename = os.path.join(os.getenv("HOME"), ".simpledcpp/favorites.xml")
		parser = make_parser()
		curHandler = SaxHandler()
		parser.setContentHandler(curHandler)
		try:
			parser.parse(open(filename))
		except IOError:
			print _("Favorites file not found.")
		for i in curHandler.setdict:
			self.tree.append((i, int(curHandler.setdict[i])))

	def add_ok(self, *args, **kwargs):
		if len(self._addentry.get_text()) > 0:
			self.hide_add()
			self.tree.append((self._addentry.get_text(), self._addcheck.get_active()))

	def _remove(self, *args, **kwargs):
		self.tree.remove(self.tree.selected_iter)
